/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.cqcis.uip.base.framework.utils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;

/**
 * UTF-8工具
 * 
 * @author huangmy
 * @date   2008-11-7
 */
public class UTF8Util {
	public final static String UTF8 = "UTF-8";
	public final static String ISO88591 = "ISO-8859-1";
	public final static String GBK = "GBK";
	public final static String GB2312 = "GB2312";
	public final static String GB18030 = "GB18030";
	
	/**
	 * 转换为UTF-8
	 * 
	 * @param s
	 * @return
	 * @throws CharacterCodingException 
	 */
    public static String encode(String s) throws Exception {
    	return new String(to(s), ISO88591);
    }
    
    /**
     * 转换为UTF-8 bytes
     * 
     * @param s
     * @return
     * @throws Exception
     */
    public static byte[] to(String s) throws Exception {
    	return to(s, UTF8);
    }
    
    public static byte[] to(String s, String charset) throws Exception {
    	ByteBuffer buffer = ByteBuffer.allocate(256).setAutoExpand(true);
    	buffer.putString(s, Charset.forName(charset).newEncoder());
    	buffer.flip();
    	
    	return buffer.array();
    }
    
    /**
     * 解码
     * 
     * @param utf8String
     * @return
     * @throws UnsupportedEncodingException 
     */
    public static String decode(String utf8String) throws UnsupportedEncodingException {
    	return new String(utf8String.getBytes(ISO88591), UTF8);
    }
    
    /**
     * 解码
     * 
     * @param utf8String
     * @return
     * @throws UnsupportedEncodingException 
     */
    public static String decode(String s, String charset) throws UnsupportedEncodingException {
    	return new String(s.getBytes(ISO88591), charset);
    }
}
